530. 二叉搜索树的最小绝对差
为保证权益,题目请参考 530. 二叉搜索树的最小绝对差(From LeetCode).
解决方案1
Python
python
from collections import deque
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def getMinimumDifference(self, root: TreeNode) -> int:
self.ans = float("inf")
self.par = -1
def middleBianLi(self, root: TreeNode) -> None:
if root is None:
return
middleBianLi(self, root.left)
# print(root.val)
if self.par != -1:
self.ans = min(self.ans, abs(root.val - self.par))
self.par = root.val
middleBianLi(self, root.right)
middleBianLi(self, root)
return self.ans
def runTest():
a = TreeNode(1)
b = TreeNode(3)
c = TreeNode(2)
a.right = b
b.left = c
S = Solution()
print(S.getMinimumDifference(a))
runTest()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45